<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index($game_id=null)
	{
        if($game_id == null){
            $this->load->view('game/index.html');
        } else {
            $this->load->model("Mlobby");
            $data["isLoggedIn"] = $this->Mlobby->checkVisitorIsPlayer($this->session->userdata("session_id"));
            if(!$data["isLoggedIn"]){
                $data["erreur"] = "Vous devez être connecté pour voir cette page<br /><a href='/lobby'>Retour à l'accueil</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            }
            $user = $this->Mlobby->getUserInfo($this->session->userdata("session_id"));
            if(!$user["isPlaying"]){
                $data["erreur"] = "Vous ne jouez pas dans ce match<br />
                    <a href='/game/watch/".$game_id."'>Accéder au match en spectateur</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            } else if($user["room"] != $game_id){
                $data["erreur"] = "Vous êtes déjà en train de jouer sur une autre room<br />
                    <a href='/game/index/".$user["room"]."'>Retour à votre partie</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            }
            
            $this->load->model("Mgame");
            $room_info = $this->Mgame->getRoomInfo($game_id);
            $data["playing"] = true;
            for($i=0; $i < count($room_info); $i++)
            {
                $r = $room_info[$i];
                if($r["hash"] == $this->session->userdata('session_id'))
                {
                    $p = "me";
                } else {
                    $p = "op";
                }
                $data["player"][$p]["pseudo"] = $r["pseudo"];
                $data["player"][$p]["hash"] = $r["hash"];
                $data["player"][$p]["perso"] = $r["perso"];
            }
            

            $data["game_id"] = $game_id;
            $this->load->view('game/index.php', $data);
        }
	}
    
    public function watch($game_id=null)
	{
        if($game_id == null){
            echo "null";
        } else {
            $this->load->model("Mlobby");
            $data["isLoggedIn"] = $this->Mlobby->checkVisitorIsPlayer($this->session->userdata("session_id"));
            if(!$data["isLoggedIn"]){
                $data["erreur"] = "Vous devez être connecté pour voir cette page<br /><a href='/lobby'>Retour à l'accueil</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            }
            $data["watchPseudo"] = $this->Mlobby->getUserInfo($this->session->userdata("session_id"));
            if($data["watchPseudo"]["isPlaying"]){
                $data["erreur"] = "Vous êtes déjà en train de jouer sur une autre room<br />
                    <a href='/game/index/".$data["watchPseudo"]["room"]."'>Retour à votre partie</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            }
            
            $this->load->model("Mgame");
            $room_info = $this->Mgame->getRoomInfo($game_id);
            if(!$room_info){
                $data["erreur"] = "Vous ne pouvez pas rejoindre un match qui n'existe pas !<br />
                    <a href='/rooms'>Retour à l'accueil</a>";
                $this->load->view("lobby/lobby_erreur.php", $data); return;
            }
            
            $data["playing"] = false;
            for($i=0; $i < count($room_info); $i++)
            {
                $r = $room_info[$i];
                if($i==0)
                {
                    $p = "me";
                } else {
                    $p = "op";
                }
                $data["player"][$p]["pseudo"] = $r["pseudo"];
                $data["player"][$p]["hash"] = $r["hash"];
                $data["player"][$p]["perso"] = $r["perso"];
            }
            
            $data["game_id"] = $game_id;
            $this->load->view('game/index.php', $data);
        }
	}
        public function create($user1, $user2)
        {
            $this->load->model("Mgame");
            $connected = $this->Mgame->getHashUsersOnline();
            if($connected != null){
                for($i = 0; $i < count($connected); $i++)
                {
                    $connected[$i] = $connected[$i]["hash"];
                }
            }
            if($connected != null && in_array($user1, $connected) && in_array($user2, $connected)){
                if(!$this->Mgame->isPlaying($user1) && !$this->Mgame->isPlaying($user2))
                {
                    $data["erreur"] = null; $data["room_id"] = $this->Mgame->createRooms($user1, $user2);
                }
                else {
                    $data['erreur'] = "Un des deux joueurs est déjà ingame. La partie a été annulée.";
                }
            } else {
                $data['erreur'] = "Un des deux joueurs n'est plus en ligne ou son ID est erroné. La partie a été annulée.";
            }
            $this->load->view("game/game_Room_id_response", $data);
        }
        
        public function oppoLeft()
        {
            $this->load->model("Mlobby");
            $user = $this->Mlobby->getUserInfo($this->session->userdata("session_id"));
            $this->load->model("Mgame");
            $oppoList = $this->Mgame->getRoomInfo($user["room"]);
            $op = null;
            foreach($oppoList as $o)
            {
                if($o["hash"] != $this->session->userdata("session_id"))
                {
                    $op = $o;
                    break;
                }
            }
            $this->Mgame->finishGame($user["room"]);
            $this->Mlobby->setExpired($op['hash']);
            $this->Mgame->modifyScore($user["pseudo"], true, false);
            $this->Mgame->modifyScore($op["pseudo"], false, true);
            $this->Mlobby->deleteExpired();
        }
        
        public function oppoWin()
        {
            $this->load->model("Mlobby");
            $user = $this->Mlobby->getUserInfo($this->session->userdata("session_id"));
            $this->load->model("Mgame");
            $oppoList = $this->Mgame->getRoomInfo($user["room"]);
            $op = null;
            foreach($oppoList as $o)
            {
                if($o["hash"] != $this->session->userdata("session_id"))
                {
                    $op = $o;
                    break;
                }
            }
            $this->Mgame->finishGame($user["room"]);
            $this->Mgame->modifyScore($user["pseudo"], false, true);
            $this->Mgame->modifyScore($op["pseudo"], true, false);
            $this->Mlobby->deleteExpired();
        }
}

/* End of file welcome.php */
/* Location: ./application/controllers/game.php */